-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathReverse-LinkedList - Recursive.py
55 lines (46 loc) · 1.26 KB
/
Reverse-LinkedList - Recursive.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Github: Shantanugupta1118
# DAY 40 of DAY 100
# Reverse LinkedList Iterative - LinkedList
class Node:
def __init__(self, data=0):
self.data = data
self.next = None
class LinkedList:
# Initializing Head Node
def __init__(self):
self.head = None
# Push new Data into New Node of LinkedList
def push(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
curr_node = self.head
while curr_node.next is not None:
curr_node = curr_node.next
curr_node.next = new_node
def disp(self):
if self.head is None:
return None
curr_node = self.head
while curr_node:
print(curr_node.data, end=' ')
curr_node = curr_node.next
print()
# Recursive Reverse
def reverse_recursive(self):
def reverseNode(prev, curr):
if curr is not None:
reverseNode(curr, curr.next)
curr.next = prev
else:
self.head = prev
reverseNode(None, self.head)
# main driver
ll = LinkedList()
arr = [int(x) for x in range(1, 10)]
for i in arr:
ll.push(i)
ll.disp()
ll.reverse_recursive()
ll.disp()